var Department = function () {

    var basePath = ROOT_PATH + 'upms/dept/',
        pagePath = ROOT_PATH + 'pages/upms/department/',
        $depGrid = null,
        $orgDept = null,
        $dialog = null,
        $form = null;
    noSelectedMsg = '请选择组织机构';
    
    function initBsGrid(treeId) {
        var op = {
            url:basePath + "list",
            gridId:treeId,
            toolbar:"#toolbar",
            columns: [
                {field: 'btSelectItem', checkbox:true},
                {field: 'id', title:"id",visible:true},
                {field: 'deptName', title:"部门"},
                {field: 'orgName', title:"所在机构"},
                {field: 'leader', title:"部门领导"},
                {field: 'status', title:"状态",formatter:FormUtils.enumFormatter,cellStyle:function(value,row,index){
                        if (value && value.code == 2){
                            return {css:{"color":"red"}}
                        }else{
                            return {css:{"color":"blue"}}
                        }
                    }},
                {field: 'createTime', title:"创建时间"},
                {field: 'opt', title:"操作",
                    formatter:function (val,row,index) {
                        return '<a href="javascript:Department.edit('+ row.id+')" class="btn btn-primary btn-xs" title="编辑"><i class="fa fa-edit">编辑</i></a> ';
                    }
                }
            ],
        };
        $depGrid =  BsGridUtil.initBsGrid(op);
        return $depGrid;
    }

    /**
     * 删除部门
     */
    function del() {
        var selectedDepartmentIds = getSelectedDepartment();
        var selected = selectedDepartmentIds;
        if (selected) {
            Dialog.confirm('确认删除部门', function (r) {
                $.Ajax({
                    url: basePath + "delete",
                    data: {id:selected.id},
                    success: function () {
                        Dialog.success("删除成功！");
                        reloadDataGrid();
                    }
                });
            });
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }


    /**
     * 获取当前已选择的部门
     * @returns {*|{js, css, dependencies}}
     */
    function getSelectedDepartment() {
        return $depGrid.bootstrapTable('getSelections')[0];
    }


    /**
     * 刷新表格
     */
    function reloadDataGrid() {
        return $depGrid.bootstrapTable('refresh');
    }

    /**
     * 创建部门
     * @param id
     * @param treeNode
     */
    function create() {
        $.Get(basePath + 'create', function (page) {
            var $dialog = $(page);
            $form = $dialog.find('form:first');
            $dialog.modal().on("shown.bs.modal", function () {
                FormUtils.disableForm($form);
                $orgDept = Organization.initReadOnlyTree($form.find("#organizationTree"),{
                    onClickRow:function (row,$ele,field) {
                        if (row._level != 0){
                            $form.find("#orgName").text(row.name);
                            $form.find("input[name='orgId']").val(row.id);
                            FormUtils.enableForm($form);
                        }else {
                            $form.find("#orgName").text("");
                            FormUtils.clearForm($form);
                            FormUtils.disableForm($form);
                        }
                    },
                    onUncheck:function () {
                        $form.find("#orgName").text("");
                        FormUtils.clearForm($form);
                        FormUtils.disableForm($form);
                    },
                    onUncheckAll:function () {
                        $form.find("#orgName").text("");
                        FormUtils.clearForm($form);
                        FormUtils.disableForm($form);
                    }
                });
                validateForm($form,$dialog);
            });
        });
    }

    function validateForm($form,$dialog) {
        FormUtils.validate($form, {
            rules: {
                deptName: {
                    maxlength: 20,
                    required: true
                },
                remark: {
                    maxlength: 100,
                }
            },
            message:{
                deptName: {
                    required: "请输入部门名称",
                    maxlength: "部门名称最大只允许10个字符"
                },
                type: {
                    maxlength:"最多允许输入100个字符"
                },
            },
            submitHandler: function () {
                var data = FormUtils.getFormObj($form);
                var url = basePath;
                if (data.id) {
                    url += "edit";
                } else {
                    url += "create";
                }
                $.Ajax({
                    url: url,
                    data: data,
                    container: $form,
                    success: function () {
                        $dialog.modal('hide');
                        $depGrid.bootstrapTable('refresh');
                        Dialog.success('操作成功');
                    }
                });
            }

        })
    }

    /**
     * 编辑
     */
    function edit(id) {
        if (id) {
            $.Get(basePath + 'edit', function (page) {
                $dialog = $(page);
                var $form = $dialog.find('form:first');
                $.Get(basePath + 'getVo', {id: id}, function (data) {
                    if (data) {
                        $dialog.modal().on('shown.bs.modal', function () {
                            FormUtils.setValues($form, data.data);
                            $orgDept = Organization.initTree($form.find("#organizationTree"));
                            dealOrgAndDeptTree($form,id);
                        })
                    } else {
                        Dialog.warning(noSelectedMsg);
                    }
                })
            })
        }
    }

    /**
     * 机构部门树处理逻辑
     */
    function dealOrgAndDeptTree($form,id) {
        //加载完成
        $orgDept.setting.callback.onAsyncSuccess = function (event, treeId, treeNode,nodes) {
            $form.find("input[name='orgId']").val(getSelectedDepartment.id);
            FormUtils.disableForm($form);
            //默认展开节点
            $orgDept.expandAll(true);
            //绑定验证事件
            validateForm($form,$dialog);
            //节点
            if (nodes.length > 0) {
                for(var i = 0;i < nodes.length;i++){
                    var nodeElement = nodes[i].id.split("-");
                    //部门类型
                    if (nodeElement[0] == 2) {
                        //选中部门
                        if (id == nodeElement[1]) {
                            var node = $orgDept.getNodeByParam("id", (nodes[i].id));
                            $orgDept.selectNode(node);
                            FormUtils.enableForm($form);
                        }
                    }
                }
            }
        }
        //点击事件
        $orgDept.setting.callback.onClick = function (event, treeId, treeNode) {
            var nodeElement = treeNode.id.split("-");
            //部门
            if (nodeElement[0] == 2){
                //是否是当前对应的
                if (id == nodeElement[1]) {
                    $form.find("input[name='id']").val(nodeElement[1]);
                    FormUtils.enableForm($form);
                }else{
                    FormUtils.disableForm($form);
                }
            }else{
                FormUtils.disableForm($form);
            }
        }
    }

    /**
     * 详情
     * @param id
     */
    function info(id) {
        if (id) {
            $.Get(pagePath + 'department-info.html', function (page) {
                $dialog = $(page);
                var $form = $dialog.find('form:first');
                $dialog.modal();
                $.Get(basePath + 'getVo', {id: id}, function (data) {
                    if (data) {
                        FormUtils.setValues($form, data.data);
                    } else {
                        Dialog.error("获取部门详情失败");
                    }
                });
            })
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }

    /**
     * 批量删除
     */
    function batchDelete() {
        var selectedDepartmentIds = getSelectedDepartment();
        var selected = selectedDepartmentIds;
        var arr = [];
        arr.push(selected.id);
        if (selectedDepartmentIds && selectedDepartmentIds.length > 0) {
            Dialog.confirm('确认删除部门', function (r) {
                $.Ajax({
                    url: basePath + "batchDelete",
                    data: {ids: arr},
                    success: function () {
                        Dialog.success("删除成功！");
                        reloadDataGrid();
                    }
                });
            });
        } else {
            Dialog.warning(noSelectedMsg);
        }
    }

    return {
        initBsGrid:initBsGrid,
        create: create,
        edit: edit,
        del: del,
        batchDelete: batchDelete,
        info: info,
    }
}();